/*************************************************************************************************************
*                                                    UTOS
*                               A non-preemptive(cooperative) multitasking RTOS Kernel
*
* Copyright (c) 2013, HuangLiang (huangliang.tj@gmail.com)
* Under New BSD license, see "LICENSE" for detail
*
* @.file       utos_sem.c
* @.version    refer to macro "UT_VERSION" in utos.h
* @.brief      
* 
*************************************************************************************************************/
#include  "utos.h"

// is_cost ->  UT_EVT_OPT_XX
void        UT_Sem_Init(void)
{
    UT_INT32U i;
    for(i=0;i<UT_SEM_MAX-1;i++)
    {
        UT_SEM_Pool[i].ptr = &UT_SEM_Pool[i+1];
    }
    UT_SEM_Pool[i].ptr  = (void*)0;          // Last one

    UT_SEM_Created_Num = 0;
    UT_SEM_Free_Entry = &UT_SEM_Pool[0];
}
UT_SEM *  UT_Sem_Create(UT_TCB *p_thrd)
{
    UT_SEM * p_sem;
    UT_EVENT *p_evt;
    if(!UT_SEM_Free_Entry)
        return (UT_SEM*)0;
    
    p_evt =  UT_Evt_Create(p_thrd);
    if(!p_evt)
        return (UT_SEM*)0;
    
    p_evt->event_type = UT_EVT_TYPE_SEM;
    p_sem = UT_SEM_Free_Entry;  
    UT_SEM_Free_Entry = (UT_SEM*)UT_SEM_Free_Entry->ptr;
    
    p_sem->ptr = p_evt;

    UT_SEM_Created_Num++;
    return p_sem;
}
UT_INT8U  UT_Sem_Delete(UT_SEM *p_sem)
{
    if(!p_sem)
        return UT_ERR_PNULL;
    UT_Evt_Delete((UT_EVENT*)p_sem->ptr);

    p_sem->ptr = UT_SEM_Free_Entry;
    UT_SEM_Free_Entry = p_sem;
    
    UT_SEM_Created_Num--;
    return UT_ERR_NONE;
}
UT_SEM *  UT_Sem_Create_Prio(UT_INT8U proc_prio, UT_INT8U thrd_prio)
{
    UT_TCB   * p_tcb;

    p_tcb = UT_Thread_Find_Thrd_Prio(proc_prio, thrd_prio);

    return UT_Sem_Create(p_tcb);
}

UT_INT8U  UT_Sem_Post(UT_SEM * p_sem)
{
    if(!p_sem)
        return UT_ERR_PNULL;

    return UT_Evt_Signal((UT_EVENT*)p_sem->ptr);
}
/*************************************************************************************************************
*                                                  END
*************************************************************************************************************/
